# coding: utf-8

import os
import cv2
import base64
import json
import capture
from huaweicloudsdkcore.auth.credentials import BasicCredentials  # type: ignore
from huaweicloudsdkfrs.v2.region.frs_region import FrsRegion       # type: ignore
from huaweicloudsdkcore.exceptions import exceptions               # type: ignore
from huaweicloudsdkfrs.v2 import *                                 # type: ignore
from config import ak,sk
from config import timeit
nameDict = {
    "BZLe5blR": (0,"陆李昕"),
    "PAlzZkWo": (1,"葛毅恒"),
    "EOOuAs0o": (2,"艾嘉豪"),
    "pmp8TlnJ": (3,"程一苓"),
}
nameList = [nameDict[key][1] for key in nameDict]

def parse_first_face_id_and_map_name(response):
    jsonobj = json.loads(str(response))
    print(jsonobj)
    first_face = jsonobj["faces"][0]
    face_id = first_face["face_id"]
    sim=first_face["similarity"]
    pos=first_face["bounding_box"]
    matched_name_dict = nameDict.get(face_id, (-1,"未找到对应姓名"))
    print(f"第一个人脸ID: {face_id}, 对应姓名: {matched_name_dict[1]}, 相似度: {sim}")
    return matched_name_dict[0],matched_name_dict[1],sim,pos
@timeit('red')
def main():
    base64str = capture.main("face.png")
    credentials = BasicCredentials(ak, sk)
    client = FrsClient.new_builder() \
        .with_credentials(credentials) \
        .with_region(FrsRegion.value_of("cn-north-4")) \
        .build()

    try:
        request = SearchFaceByBase64Request()
        request.face_set_name = "ICT"  # 请更改为实际的人脸库名称
        request.body = FaceSearchBase64Req(
            image_base64=base64str
        )
        response = client.search_face_by_base64(request)
        matched_name,sim,pos = parse_first_face_id_and_map_name(response)
        return matched_name,sim,pos
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

if __name__ == "__main__":
    main()

